package sysmodel

import (
	"context"
	"group-card/common/tool"
	"group-card/model/entity"
	"xorm.io/xorm"
)

var _ SysCustomerModel = (*customSysCustomerModel)(nil)

type (
	// SysCustomerModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSysCustomerModel.
	SysCustomerModel interface {
		sysCustomerModel
		List(ctx context.Context, req *entity.SysCustomerReq) ([]*entity.SysCustomerResp, int64, error) // 分页查询
	}

	customSysCustomerModel struct {
		*defaultSysCustomerModel
	}
)

// NewSysCustomerModel returns a model for the database table.
func NewSysCustomerModel(conn *xorm.Engine) SysCustomerModel {
	return &customSysCustomerModel{
		defaultSysCustomerModel: newSysCustomerModel(conn),
	}
}

func (m *defaultSysCustomerModel) List(ctx context.Context, req *entity.SysCustomerReq) ([]*entity.SysCustomerResp, int64, error) {
	sql := m.conn.Table(m.table)

	if req.Columns != "" {
		sql.Select(req.Columns)
	}

	if req.Id != 0 {
		sql.Where("id = ?", req.Id)
	}

	if req.Name != "" {
		sql.Where("name like ?", "%"+req.Name+"%")
	}

	if req.Area != "" {
		sql.Where("area like ?", "%"+req.Area+"%")
	}

	if req.Status != 0 {
		sql.Where("status = ?", req.Status)
	}

	list := make([]*entity.SysCustomerResp, 0)
	count, err := sql.Limit(int(req.PageSize), int((req.PageNum-1)*req.PageSize)).FindAndCount(&list)
	if err != nil {
		tool.GLogLine("获取集团客户列表失败 defaultSysCustomerModel List:", err)
		return nil, 0, err
	}

	return list, count, err
}
